package com.green.web.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

@Component
public class FileUtils {

    /**
     * 因为这个变量是静态的，所以需要通过set方法进行注入
     * 并且该类需要交给spring管理
     */
    private static String uploadPath;

    @Value("${stt.upload_path}")
    public void setUploadPath(String uploadPath) {
        FileUtils.uploadPath = uploadPath;
    }


    /**
     * 文件上传
     * @param file
     * @return
     */
    public static String upload(MultipartFile file) throws IOException {
        //重命名文件
        String fileName = extractFileName(file);
        System.out.println("新的文件名为:" + fileName);
        //获取文件上传路径
        String absFile = getAbsoluteFile(fileName).getAbsolutePath();
        //文件上传
        file.transferTo(Paths.get(absFile));
        return fileName;
    }

    /**
     * 编码文件名
     *
     * @param
     * @return
     */
    public static final String extractFileName(MultipartFile file) {

        //重名文件名   ABC.ppt
        //1.生成新的文件名，通过UUID或者其他工具类生产
        String newFileName = UUID.randomUUID().toString();
        System.out.println("newFileName==>" + newFileName);
        //替换-
        newFileName = newFileName.replaceAll("-", "");
        System.out.println("替换后newFileName==>" + newFileName);
        //2获取源文件的文件类型
        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        return newFileName + "." + suffixName;
    }

    /**
     * 获取文件后缀
     *
     * @param file
     * @return
     */
    public static Object getExtension(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        return originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
    }


    public static final File getAbsoluteFile(String fileName) throws IOException {
        //创建File
        //uploadPath文：文件根路径
        //File.separator根据操作系统生成分隔符
        //拼接结果   D:\\temp\\新文件名.后缀
        File desc = new File(uploadPath + File.separator + fileName);
        //判断是否存在
        if (!desc.exists()) {
            //判断付路径是否存在
            if (!desc.getParentFile().exists()) {
                //创建路径下多级文件夹
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }
}
